import { defineStore } from 'pinia';
import router from '@/router';
import { useXmRouter } from '@/stores/XmRouter';

export class UserInfo {
  gender = '';
  archiveFlag = '';
  loginName = '';
  isLocked = '';
  mobile = '';
  userType = '';
  userName = '';
  userId = '';
  email = '';
  status = '';
}

export const userStore = defineStore('user', {
  state: () => ({
    loginName: '',
    username: '',
    xToken: '',
    loginStatus: true,
    userData: new UserInfo(),
    token: '',
    headimgurl: '',
    nickname: '',
    phone:'',
    gzCode:''
  }),
  getters: {
    isLogin() {
      return this.loginStatus && !!this.xToken && this.xToken.length > 0;
    },
    getToken(){
      return this.token;
    },
    getHeadimgurl(){
      return this.headimgurl;
    },
    getNickname(){
      return this.nickname;
    },
    getUsername(){
      return this.username;
    },
    getPhone(){
      return this.phone;
    },
    getGZCode(){
      return this.gzCode;
    }
  },
  actions: {
    setUserInfo(token, headimgurl, nickname) {
      this.token = token;
      this.headimgurl = headimgurl;
      this.nickname = nickname;
    },
    setUserNameTel(username, tel) {
      this.username = username;
      this.phone = tel;
    },
    setGZCode(code) {
      this.gzCode = code;
    },
    clearZCCode(){
      this.gzCode = '';
    },
    loginSuccess(xToken, loginName) {
      this.xToken = xToken;
      this.loginName = loginName;
      this.loginStatus = true;
    },
    async logout() {
      this.clearUserInfo();
      useXmRouter().clear();
      await router.replace('/login');
    },
    clearUserInfo() {
      this.loginStatus = false;
      this.loginName = '';
      this.username = '';
      this.xToken = '';
      this.userData = new UserInfo();
    }
  }
});

export const useUserStore = () => {
  return userStore();
};
